package user

import (
	"context"
	"github.com/jinzhu/copier"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/xerr"
	"strings"

	"navi-mumbai/app/api/business/internal/svc"
	"navi-mumbai/app/api/business/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginReq, ip string) (resp *types.UserLoginResp, err error) {
	l.Logger.Infof("UserLogin username %s ip %s, AppsFlyerUID: %s", req.Username, ip, req.AppsFlyerUID)
	if req.Passwd == "" || req.Username == "" {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "username or passwd is empty")
	}
	var in pb.LoginUserReq
	in.UserPass = req.Passwd
	in.AuthType = userkey.UserAuthTypePasswd
	in.AuthKey = req.Username
	in.Pid = req.Pid
	if ip != "" {
		ips := strings.Split(ip, ",")
		if len(ips) > 0 {
			in.Ip = ips[0]
		}
	}
	in.AppVer = req.AppVer
	in.UserChannel = req.UserChannel
	in.Device = req.Device
	in.DeviceId = req.DeviceId
	in.AppsFlyerUID = req.AppsFlyerUID

	var rsp *pb.LoginUserResp
	rsp, err = l.svcCtx.UcUserRpc.Login(l.ctx, &in)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	resp = &types.UserLoginResp{
		Token:   &types.UserToken{},
		Account: &types.UserAccount{},
		Profile: &types.UserProfile{},
	}
	_ = copier.Copy(resp, rsp)
	return
}
